package com.tbit.uqbike.service.business.impl;

import com.tbit.common.config.OssDefaultConfig;
import com.tbit.uqbike.annos.EncapsulateMap;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.*;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.service.business.AccountService;
import com.tbit.uqbike.service.business.AdaccountService;
import com.tbit.uqbike.service.business.ImageService;
import com.tbit.uqbike.service.business.OssConfigService;
import com.tbit.uqbike.service.rpcservice.PurviewService;
import com.tbit.uqbike.webmanager.dao.core.AdaccountDao;
import com.tbit.uqbike.webmanager.util.FileLoadUtils;
import com.tbit.uqbike.webmanager.util.LogUtil;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.uqbike.webmanager.util.aliyun.OssFileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

/**
 * @author chenmengran
 * @Description: 运营区域广告
 * @date 2020\1\7 000714:13
 */
@Slf4j
@Service(value = "adaccountService")
@AllArgsConstructor
public class AdaccountServiceImpl implements AdaccountService {
    @Autowired
    private AdaccountDao adaccountDao;
    @Autowired
    private ImageService imageService;
    @Autowired
    private PurviewService purviewService;
    @Autowired
    private OssConfigService ossConfigService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private OssDefaultConfig ossDefaultConfig;

    @Override
    public List<Adaccount> queryPage(Integer accountId, Integer type, String sortName,
                                     Integer rowCount, Integer pageNO) {

        Map<String, Object> params = new HashMap<>();
        params.put("accountId", accountId);
        params.put("type", type);
        params.put("sortName", sortName);
        params.put("start", (pageNO - 1) * rowCount);
        params.put("rowCount", rowCount);

        return adaccountDao.queryPage(params);
    }

    @Override
    public Integer getTotal(Integer accountId, Integer type) {
        Map<String, Object> params = new HashMap<>();
        params.put("accountId", accountId);
        params.put("type", type);

        return adaccountDao.getTotal(params);
    }

    @Override
    public void addTopAdvert(Integer accountId, Integer type, String title, String openURL, String remark, Long startTime, Long endTime) {
        Map<String, Object> params = new HashMap<>();
        params.put("accountId", accountId);
        params.put("adType", type);
        params.put("updateTime", new Date());
        params.put("title", title);
        params.put("openURL", openURL);
        if (startTime != null) {
            params.put("startTime", new Date(startTime));
        }
        if (endTime != null) {
            params.put("endTime", new Date(endTime));
        }
        if (remark != null) {
            params.put("remark", remark);
        }

        adaccountDao.insert(params);
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public void addAdvert(Integer accountId, MultipartFile[] file, Integer type, String title, String openURL, String remark, Long startTime, Long endTime) {
        try {
            String imageId = null;
            String name = null;
            for (MultipartFile multipartFile : file) {
                if (!FileLoadUtils.checkFileSize(multipartFile, 2, "M")) {
                    throw new BaseException(SystemCodeEnum.IMAGE_SIZE_LIMIT2M);
                }
                InputStream inputStream = multipartFile.getInputStream();
                /**阿里云配置*/
                OssConfig ossConfig = new OssConfig(ossDefaultConfig.getEndpoint(),
                        ossDefaultConfig.getAccessKeyId(),
                        ossDefaultConfig.getAccessKeySecret(), "gx-res");
                Account account = accountService.getAgentId(accountId);
                /**查询是否存在配置信息*/
                OssConfig ossConfigDB = ossConfigService.getByAccountId(account.getParentId());
                if (ossConfigDB != null) {
                    ossConfig = ossConfigDB;
                }
                //添加图片
                imageId = UUID.randomUUID().toString();
                /**上传阿里云*/
                String fileName = OssFileUtils.uploadByAliYun(inputStream, ossConfig, imageId, multipartFile.getContentType(), OssFileUtils.IMAGE);
                name = fileName;
                Image image = new Image();
                image.setImageId(fileName);
                image.setCreateTime(new Date());
                image.setImageType(multipartFile.getContentType());
                image.setImageContent(multipartFile.getBytes());
                imageService.setImage(image);
            }
            //Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);
            //添加绑定关系
            Map<String, Object> params = new HashMap<>();
            params.put("accountId", accountId);
            params.put("adType", type);
            params.put("imageId", name);
            params.put("updateTime", new Date());
            params.put("title", title);
            params.put("openURL", openURL);
            if (startTime != null) {
                params.put("startTime", new Date(startTime));
            }
            if (endTime != null) {
                params.put("endTime", new Date(endTime));
            }
            if (remark != null) {
                params.put("remark", remark);
            }
            adaccountDao.insert(params);
        } catch (Exception e) {
            LogUtil.info("图片上传失败 ：");
            LogUtil.info(e.toString());
            throw new BaseException(SystemCodeEnum.IMAGE_PUT_FAIL);
        }

    }

    @Override
    //@Transactional
    public void delAdvert(LoginInfo loginInfo, Integer adId) {
        Adaccount adaccount = adaccountDao.getById(adId);
        if (adaccount != null) {
            if (!purviewService.purviewCheck(loginInfo.id, adaccount.getAccountId())) {
                throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
            }
            if (adaccount.getAdType() != 2 && adaccount.getImageId() != null && !"".equals(adaccount.getImageId())) {
                //删除图片
                imageService.delByImageId(adaccount.getImageId());
            }
            //删除绑定关系
            adaccountDao.del(adId);
        }
    }

    @Override
    @EncapsulateMap
    public void update(Map<String, Object> params, Integer adId, Integer sort, String openURL) {
        adaccountDao.update(params);
    }

    @Override
    public void editAdvertConfig(AdvertConfig advertConfig) {
        Map<String, Object> params = new HashMap<>();
        params.put("accountId", advertConfig.getAccountId());
        params.put("advertType", advertConfig.getAdvertType());
        params.put("advertSwitch", advertConfig.getAdvertSwitch());
        params.put("advertPosition", advertConfig.getAdvertPosition());
        params.put("adType", advertConfig.getAdType());
        if (!adaccountDao.getAdvertConfig(params).isEmpty()) {
            adaccountDao.updateAdvertConfig(params);
        } else {
            adaccountDao.insertAdvertConfig(advertConfig);
        }
    }

    @Override
    public List<AdvertConfig> getAdvertConfig(AdvertConfig advertConfig) {
        Map<String, Object> params = new HashMap<>();
        params.put("accountId", advertConfig.getAccountId());
        params.put("advertType", advertConfig.getAdvertType());
        params.put("advertSwitch", advertConfig.getAdvertSwitch());
        params.put("advertPosition", advertConfig.getAdvertPosition());
        params.put("advertNo", advertConfig.getAdvertNo());

        return adaccountDao.getAdvertConfig(params);
    }

    @Override
    public Integer addAdvertNo(AdvertConfig advertConfig) {
        Map<String, Object> params = new HashMap<>();
        params.put("accountId", advertConfig.getAccountId());
        params.put("advertType", advertConfig.getAdvertType());
        params.put("advertSwitch", advertConfig.getAdvertSwitch());
        params.put("advertPosition", advertConfig.getAdvertPosition());
        params.put("advertNo", advertConfig.getAdvertNo());
        return adaccountDao.updateAdvertConfig(params);
    }

    @Override
    public void updateAdvert(Integer accountId, MultipartFile[] file, Integer type, String title, String openURL, String remark, Long startTime, Long endTime, String url, LoginInfo loginInfo, Integer adId) {
        if (StringUtils.isEmpty(url)) {
            //重新上传了图片
            delAdvert(loginInfo, adId);
            addAdvert(accountId, file, type, title, openURL, remark, startTime, endTime);
        } else {
            //更新除了图片外的其他参数
            adaccountDao.updateAdvert(type, title, remark, new Date(startTime), new Date(endTime), adId, openURL);
        }
    }

    @Override
    public void updateAdAccountIdFlowNo() {
        //查询所有区域广告配置
        List<AdvertConfig> adAccountAdvertConfigList = adaccountDao.selectAllAdAccountAdvertConfig();
        adAccountAdvertConfigList.forEach(a -> adaccountDao.updateToFollowBrand(a.getAccountId(), a.getAdvertType(), a.getAdvertPosition()));
    }

    @Override
    public List<Adaccount> getListByType(Integer type) {
        return adaccountDao.selectListByType(type);
    }


}
